package model;

import util.AppUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

import constant.Msg;

public class Moment extends Model<Moment> {
	private static final long serialVersionUID = 1L;
	public static final Moment dao = new Moment();
	public static final String getCountSql = "select count(*) as num from moments where 1=1;";/* 数据交互 *//* select */
	public static final String getMomentsSql = "select id,userId,content,images,create_time,update_time from moments ";
	
	public String selectById(Integer id, int userId) {
		try {
			Moment moment = Moment.dao.findById(id);
			User user = User.dao.findById(moment.getInt("userId"));
			moment.put("nickname", user.getStr("nickname"));
			moment.put("avatar", user.getStr("avatar"));
			List<Zan> zan=Zan.dao.find(Zan.findSQL,userId,id,1);
			if(zan.size()==0) moment.put("star",false);
			else if(zan.size()==1){
				if(zan.get(0).getInt("status")==1)
					moment.put("star", true);
				else moment.put("star", false);
			}else return Msg.ERROR_UNKNOWN;
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "成功");
			JSONObject data = new JSONObject();
			for (String attr : moment._getAttrNames()) {
				data.put(attr, moment.get(attr));
			}
			JSONArray array = new JSONArray(); 
			for (RecipeComment comment : RecipeComment.dao.find(RecipeComment.showCommentsSQL,id)) {
				JSONObject js = new JSONObject();
				for (String attr : comment._getAttrNames()) {
					js.put(attr, comment.get(attr));
				}
				array.add(js);
			}
			data.put("comments", array);
			json.put("data", data);
			
			
			return json.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}/* insert */

	public boolean add(Moment moment) {
		try {
			moment.save();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}/* delete */

	public boolean delete(Integer id) {
		try {
			Moment.dao.deleteById(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}/* update */

	public boolean update(Moment moment) {
		try {
			StringBuffer updateSql = new StringBuffer("update moments set ");
			Map<String, String> attrMap = AppUtil.getAttr(moment);
			for (Map.Entry<String, String> entry : attrMap.entrySet()) {
				updateSql.append(entry.getKey() + "=");
				if (!AppUtil.isNum(entry.getValue())) {
					updateSql.append("\"" + entry.getValue() + "\"");
				} else {
					updateSql.append(entry.getValue());
				}
				updateSql.append(",");
			}
			updateSql.deleteCharAt(updateSql.length() - 1);
			updateSql.append(" where id=" + moment.getStr("id"));
			System.out.println(updateSql.toString());
			Db.update(updateSql.toString());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean add(int userId, String content, String images) {
		try {
			Moment moment = new Moment()
					.set("content", content)
					.set("images", images)
					.set("userId",userId)
					.set("create_time",
							(int) (System.currentTimeMillis() / 1000));
			return add(moment);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean update(Integer id, String content, String images) {
		try {
			Moment moment = new Moment()
					.set("id", id)
					.set("content", content)
					.set("images", images)
					.set("update_time",
							(int) (System.currentTimeMillis() / 1000));
			return update(moment);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/*
	 * 1. 没有hot字段
	 * 2. 默认按时间排序
	 * 3. 所以sort字段只能是create_time或update_time
	 * 4. 用update_time可能会出错，因为该字段可能为null
	 */
	
	public String select(String sort, String order, String offset, String length) {
		try {
			if(offset==null) offset = "0";
			if(length==null) length = "10";
			List<Moment> momentList = new ArrayList<Moment>();
			String finsql = "";
			if(sort!=null){
				if(order!=null && "desc".equals(order.toLowerCase())){
					finsql = getMomentsSql+"order by "+sort+" desc";
				}else{
					finsql = getMomentsSql+"order by "+sort;
				}
			}else{
				if(order!=null && "desc".equals(order.toLowerCase())){
					finsql = getMomentsSql+"order by create_time desc";
				}else{
					finsql = getMomentsSql;
				}
			}
			finsql = finsql + "limit "+offset+", "+length+";";
			momentList = Moment.dao.find(finsql);
			for (Moment moment : momentList) {
				User user = User.dao.findById(moment.getInt("userId"));
				moment.put("nickname", user.getStr("nickname"));
				moment.put("avatar", user.getStr("avatar"));
			}
			return AppUtil.modelToJson(momentList);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}/* 工具部分 *//* 获取总条数 */

	public int getCount() {
		int num = 0;
		num = Db.find(getCountSql).get(0).getInt("num");
		return num;
	}

	public int getPage(Integer length) {
		int num = getCount();
		if (num == 0)
			return 0;
		return num % length == 0 ? num / length : (num / length) + 1;
	}/* 验证函数 *//* 偏移量超出检测 */

	public boolean checkOffsetOut(Integer offset) {
		if (offset >= getCount())
			return false;
		else
			return true;
	}
}
